Telegram Group & Telegram Channel
🎯 Как быстро настроить кеширование в Spring Boot

Писать кеш руками через HashMap или страдать с вручную настроенными TTL — скучно, долго и ненадёжно. В Spring Boot всё уже готово: включаем, настраиваем, и поехали!

1️⃣ Добавляем зависимость

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

ИЛИ

implementation 'org.springframework.boot:spring-boot-starter-cache'


2️⃣ Включаем кеширование

Добавляем простую аннотацию над главным классом приложения (или конфиг классом):
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}


3️⃣ Кешируем методы сервисов

Используем аннотацию @Cacheable на тех методах, которые часто выполняются и редко меняются:
@Service
public class UserService {

@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
simulateSlowService();
return userRepository.findById(id).orElseThrow();
}

private void simulateSlowService() {
Thread.sleep(3000);
}
}


Теперь при повторном вызове метода с тем же параметром ответ прилетит мгновенно.

4️⃣ Настройка TTL и конфигурация кеша

В Spring Boot по умолчанию используется простой ConcurrentMap (без TTL). Если хочешь TTL и прочие плюшки, подключайте Caffeine:

spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=500,expireAfterAccess=10m


Кеш будет жить максимум 10 минут и не разрастаться до бесконечности.

5️⃣ Очистка кеша

Если нужно принудительно почистить кеш после обновления данных, используем @CacheEvict:
@CacheEvict(value = "users", key = "#id")
public void updateUser(Long id, User updatedUser) {
userRepository.save(updatedUser);
}


💬 Хранили когда-нибудь кеш в мапе?

🐸 Библиотека джависта #буст
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/javaproglib/6561
Create:
Last Update:

🎯 Как быстро настроить кеширование в Spring Boot

Писать кеш руками через HashMap или страдать с вручную настроенными TTL — скучно, долго и ненадёжно. В Spring Boot всё уже готово: включаем, настраиваем, и поехали!

1️⃣ Добавляем зависимость

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

ИЛИ

implementation 'org.springframework.boot:spring-boot-starter-cache'


2️⃣ Включаем кеширование

Добавляем простую аннотацию над главным классом приложения (или конфиг классом):
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}


3️⃣ Кешируем методы сервисов

Используем аннотацию @Cacheable на тех методах, которые часто выполняются и редко меняются:
@Service
public class UserService {

@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
simulateSlowService();
return userRepository.findById(id).orElseThrow();
}

private void simulateSlowService() {
Thread.sleep(3000);
}
}


Теперь при повторном вызове метода с тем же параметром ответ прилетит мгновенно.

4️⃣ Настройка TTL и конфигурация кеша

В Spring Boot по умолчанию используется простой ConcurrentMap (без TTL). Если хочешь TTL и прочие плюшки, подключайте Caffeine:

spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=500,expireAfterAccess=10m


Кеш будет жить максимум 10 минут и не разрастаться до бесконечности.

5️⃣ Очистка кеша

Если нужно принудительно почистить кеш после обновления данных, используем @CacheEvict:
@CacheEvict(value = "users", key = "#id")
public void updateUser(Long id, User updatedUser) {
userRepository.save(updatedUser);
}


💬 Хранили когда-нибудь кеш в мапе?

🐸 Библиотека джависта #буст

BY Библиотека джависта | Java, Spring, Maven, Hibernate




Share with your friend now:
tg-me.com/javaproglib/6561

View MORE
Open in Telegram


Библиотека джависта | Java Spring Maven Hibernate Telegram | DID YOU KNOW?

Date: |

Telegram auto-delete message, expiring invites, and more

elegram is updating its messaging app with options for auto-deleting messages, expiring invite links, and new unlimited groups, the company shared in a blog post. Much like Signal, Telegram received a burst of new users in the confusion over WhatsApp’s privacy policy and now the company is adopting features that were already part of its competitors’ apps, features which offer more security and privacy. Auto-deleting messages were already possible in Telegram’s encrypted Secret Chats, but this new update for iOS and Android adds the option to make messages disappear in any kind of chat. Auto-delete can be enabled inside of chats, and set to delete either 24 hours or seven days after messages are sent. Auto-delete won’t remove every message though; if a message was sent before the feature was turned on, it’ll stick around. Telegram’s competitors have had similar features: WhatsApp introduced a feature in 2020 and Signal has had disappearing messages since at least 2016.

Find Channels On Telegram?

Telegram is an aspiring new messaging app that’s taking the world by storm. The app is free, fast, and claims to be one of the safest messengers around. It allows people to connect easily, without any boundaries.You can use channels on Telegram, which are similar to Facebook pages. If you’re wondering how to find channels on Telegram, you’re in the right place. Keep reading and you’ll find out how. Also, you’ll learn more about channels, creating channels yourself, and the difference between private and public Telegram channels.

Библиотека джависта | Java Spring Maven Hibernate from hk


Telegram Библиотека джависта | Java, Spring, Maven, Hibernate
FROM USA